<script setup>
const router = useRouter()

// 表单数据
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const nickname = ref('')

// 使用注册API
const { runAsync: register, loading } = registerApi()

// 自定义校验规则：确认密码
const validateConfirmPassword = value => {
  if (!value) return '请再次输入密码'
  if (value !== password.value) return '两次输入的密码不一致'
  return true
}

// 注册方法
const handleRegister = async () => {
  try {
    // 加密密码
    const encryptedPassword = md5EncryptWithSalt(password.value)

    // 调用注册API
    await register({
      username: username.value,
      password: encryptedPassword,
      nickname: nickname.value || username.value
    })

    showToast('注册成功，请登录')

    // 注册成功后跳转到登录页
    router.replace('/login')
  } catch (error) {
    console.error('注册失败:', error)
    showToast(error?.message || '注册失败，请重试')
  }
}

// 返回登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<template>
  <div class="min-h-screen bg-gray-100 flex flex-col">
    <div class="mt-auto pb-safe bg-white rounded-t-[32px] pt-10 pb-10 px-6 min-h-[60vh] shadow-lg">
      <h2 class="text-center text-2xl font-bold mb-10 text-gray-900">注册</h2>
      <van-form @submit="handleRegister">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="nickname"
            name="nickname"
            label="昵称"
            placeholder="请输入昵称（选填）"
          />
          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field
            v-model="confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="[{ validator: validateConfirmPassword }]"
          />
        </van-cell-group>
        <div class="mt-10">
          <BaseButton
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            class="w-full"
          >
            注册
          </BaseButton>
          <div class="mt-8 text-center text-sm text-gray-500">
            <span>已有账号？</span>
            <span class="text-blue-500 ml-1 cursor-pointer font-medium" @click="goToLogin"
              >返回登录</span
            >
          </div>
        </div>
      </van-form>
    </div>
  </div>
</template>
<route>
  { 
    path: '/register',
    name: 'register',
    meta: {
      title: '注册',
      hideTabbar: true,
    }
  }
</route>
